package cn.com.elite;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import cn.com.elite.util.Util;
import cn.com.eliteUtil.MeiLian;

public class EliteThresd implements Runnable{
	private static final Log log=LogFactory.getLog(EliteThresd.class);
	private boolean flag = true; //停止线程标记 
	private static int Hz=30; 
	private static String POST_URL123=""; 
	private static int trytime=10; 
	public static cn.com.elite.EliteForBean ebean;
	private Map list;
		
	public Map getList() {
		return list;
	}

	public void setList(Map list) {
		this.list = list;
	}

	public static cn.com.elite.EliteForBean getEbean() {
		return ebean;
	}

	public static void setEbean(cn.com.elite.EliteForBean ebean) {
		EliteThresd.ebean = ebean;
	}

	public static int getTrytime() {
		return trytime;
	}

	public static void setTrytime(int trytime) {
		EliteThresd.trytime = trytime;
	}

	public static int getHz() {
		return Hz;
	}

	public static void setHz(int hz) {
		Hz = hz;
	}

	public static String getPOST_URL123() {
		return POST_URL123;
	}

	public static void setPOST_URL123(String post_url123) {
		POST_URL123 = post_url123;
	}

	public void run(){
		while(flag){
			try{
				log.info("-------------------------run()---------------------------------");
				if(list!=null&&list.size()>0){
					    log.info("-------------------------list!=null&&list.size()>0---------------------------------");
						Iterator iter=list.entrySet().iterator(); 
						Map map_temp= new HashMap();
						while(iter.hasNext()){
							Map.Entry entry=(Map.Entry)iter.next(); 
						    Map map1=(Map)entry.getValue(); 
						    String guid=Util.filter((String)map1.get("Guid"));
							String URL=Util.filter((String)map1.get("URL"));
							String Method=Util.filter((String)map1.get("Method"));
							String FromCode=Util.filter((String)map1.get("FromCode"));
							String ToCode=Util.filter((String)map1.get("ToCode"));
							String Content=Util.filter((String)map1.get("Content"));
							String HeadStr=Util.filter((String)map1.get("HeadStr"));
							int count=(Integer)map1.get("count");
							String POST_URL="";
							POST_URL=POST_URL+"&URL="+URL;
							POST_URL=POST_URL+"&Method="+Method;
							POST_URL=POST_URL+"&FromCode="+FromCode;
							POST_URL=POST_URL+"&ToCode="+ToCode;
							POST_URL=POST_URL+"&Content="+URLEncoder.encode(Content,"UTF-8");
							POST_URL=POST_URL+"&HeadStr="+HeadStr;
							int judge=0;
							String returnString=get_interface_return(POST_URL123,POST_URL);	
							log.info("returnString:"+returnString);
							returnString=returnString.replace("utf-8","gb2312");
							log.info("returnString:"+returnString);
							String sql="";
							if(returnString!=null&&returnString.length()>0){
								MeiLian meiLian=new MeiLian();
								String MeiLianResult=meiLian.getresult(returnString);
								log.info("MeiLianResult:"+MeiLianResult);
								if(!MeiLianResult.equals("")&&!MeiLianResult.equals("0")){
									count=count+1;
									map1.put("count",count);
									sql=" update eliteforward set succ_flag=1,modifydate=getdate(),result='"+returnString+"',trytimes="+count+" where GUID='"+guid+"'";
									log.info("返回成功");
									judge=1;
									map_temp.put(guid,guid);
								}else{
									count=count+1;
									map1.put("count",count);
									sql=" update eliteforward set modifydate=getdate(),result='"+returnString+"',trytimes="+count+" where GUID='"+guid+"'";
									log.info("返回失败");
								}
							}else{
								count=count+1;
								map1.put("count",count);
								sql=" update eliteforward set modifydate=getdate(),result='"+returnString+"',trytimes="+count+" where GUID='"+guid+"'";
							}
							int result=ebean.update_sql(sql);
							log.info(sql+":"+result);
                            if(judge==0&&count>=trytime){
                            	log.info("remove:guid:"+guid+";count:"+count);
                            	map_temp.put(guid,guid);
                            }else{
                            	log.info("keep:guid:"+guid+";count:"+count);
                            }
						}
						log.info("map_temp:"+map_temp);
						Iterator iter_temp=map_temp.entrySet().iterator(); 
						while(iter_temp.hasNext()){
							Map.Entry entry=(Map.Entry)iter_temp.next(); 
							String guid123=(String)entry.getValue(); 
						    synchronized(list){
						    	list.remove(guid123);
						    }
						}
						
				}
			}catch(Exception e){
				log.error("run():"+Util.getERRO(e));
			}
			try{
				log.info("Hz:"+Hz);
            	Thread.sleep(Hz*1000);
            }catch(Exception e){
            	log.error("定时错误:"+Util.getERRO(e)); 
            }
		}	
		log.info("flag:"+flag);
	}

	public static String get_interface_return(String address,String Parm) throws Exception{
		String returnxml="";
		URL url=new URL(address);
		HttpURLConnection conn=(HttpURLConnection)url.openConnection();
		conn.setRequestMethod("POST");
		conn.setUseCaches(false);
		conn.setInstanceFollowRedirects(true);
		conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
		conn.setConnectTimeout(60000);
		conn.setReadTimeout(60000);
		conn.setDoOutput(true);
		conn.connect();
		DataOutputStream out=new DataOutputStream(conn.getOutputStream()); 
		out.writeBytes(Parm); 
        out.flush();
        out.close();
        BufferedReader rd=new BufferedReader(new InputStreamReader(conn.getInputStream(),"UTF-8")); 
		returnxml=rd.readLine(); 
		rd.close();
        conn.disconnect();
        return returnxml;
	}

}
